﻿using System.Drawing.Imaging;
using System.Drawing;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio.DataModel.Args;
using Minio;
using ThoughtWorks.QRCode.Codec;
using DataManageSystem.Services;
using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class QRCodeController : ControllerBase
    {
        private readonly MinioClient _minioClient;
        private readonly ApplicationDbContext _context;
        private readonly string _bucketName = "qrcode-bucket"; // MinIO 存储桶名称
        private readonly string _minioUrl = "http://139.196.170.188:9000"; // MinIO 访问地址
        private readonly OfficeDevicesServices officeDevicesServices;

        public QRCodeController(OfficeDevicesServices officeDevicesServices, ApplicationDbContext context)
        {
            this.officeDevicesServices = officeDevicesServices;
            this._context = context;
            _minioClient = (MinioClient?) new MinioClient()
                .WithEndpoint("139.196.170.188:9000")
                .WithCredentials("kecheng", "lkclkclkc")
                .Build();
        }

        [HttpGet("generate")]
        public async Task<ObjectResult> GenerateAndUploadQRCode([FromQuery] string id)
        {
            var officeDevices = officeDevicesServices.GetDeviceInfo(id);
            if (string.IsNullOrEmpty(officeDevices.DeviceCode))
            {
                return new ObjectResult(Result.Error("设备编码不能为空"));
            }
            string text = officeDevices.DeviceCode;

            if (string.IsNullOrWhiteSpace(text))
            {
                return BadRequest("二维码内容不能为空");
            }

            try
            {
                // 生成二维码图片
                using var qrImage = GenerateQRCode(text);

                // 保存为临时文件流
                using var ms = new MemoryStream();
                qrImage.Save(ms, ImageFormat.Png);
                ms.Position = 0; // 复位流位置

                // 生成唯一的文件名
                string objectName = $"qrcode_{Guid.NewGuid()}.png";

                // 确保 MinIO 存储桶存在
                bool found = await _minioClient.BucketExistsAsync(new BucketExistsArgs().WithBucket(_bucketName));
                if (!found)
                {
                    await _minioClient.MakeBucketAsync(new MakeBucketArgs().WithBucket(_bucketName));
                }

                // 上传二维码图片到 MinIO
                var putObjectArgs = new PutObjectArgs()
                    .WithBucket(_bucketName)
                    .WithObject(objectName)
                    .WithStreamData(ms)
                    .WithObjectSize(ms.Length)
                    .WithContentType("image/png");

                await _minioClient.PutObjectAsync(putObjectArgs);

                // 生成二维码文件的访问 URL
                string fileUrl = $"{_minioUrl}/{_bucketName}/{objectName}";

                // 更新设备信息
                officeDevices.DeviceInfoCode = fileUrl;

                _context.OfficeDevices.Update(officeDevices);
                await _context.SaveChangesAsync();

                return new ObjectResult(Result.Success(fileUrl));
            }
            catch (Exception ex)
            {
                
                return new ObjectResult(Result.Error("二维码生成或上传失败：" + ex.Message));
            }
        }

            private Bitmap GenerateQRCode(string text, int size = 10)
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // 解决 GB2312 问题
                QRCodeEncoder qrEncoder = new QRCodeEncoder
                {
                    QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
                    QRCodeScale = size,
                    QRCodeVersion = 5,
                    QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q // 高容错
                };
                return qrEncoder.Encode(text);
        }
    }
}
